package com.study.forumsystemproject.exception;

import com.study.forumsystemproject.common.Result;
import com.study.forumsystemproject.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * program: forum-system-project
 * <p>
 * description: 统一异常处理
 * <p>
 * author: xiaoxie
 * <p>
 * create: 2024-08-14 20:49
 **/
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /** 处理⾃定义的已知异常
     * Description: handleApplicationException
     * Param: * @param e
     * return: com.study.forumsystemproject.common.Result
     * Author: xiaoxie
     * Date: 20:54 2024/8/14
    */
    @ResponseBody
    @ExceptionHandler(value = ApplicationException.class)
    public Result handleApplicationException(ApplicationException e) {
        log.error(e.getMessage());
        if(e.getErrorResult() != null) {
            return e.getErrorResult();
        }
        //出现异常描述为空的情况
        if(e.getMessage() == null || "".equals(e.getMessage())) {
            return Result.fail(ResultCode.ERROR_SERVICES);
        }
        return Result.fail(e.getMessage());
    }

    /** 处理一些未知异常
     * Description: handleException
     * Param: * @param e
     * return: com.study.forumsystemproject.common.Result
     * Author: xiaoxie
     * Date: 21:01 2024/8/14
    */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        log.error(e.getMessage());
        if (e.getMessage() == null || "".equals(e.getMessage())) {
            return Result.fail(ResultCode.ERROR_SERVICES);
        }
        return Result.fail(e.getMessage());
    }
}
